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"
23 #include "socketengine.h"
25 #include "command_parse.h"
27 bool InspIRCd::ULine(const char* server)
34 return (find(Config->ulines.begin(),Config->ulines.end(),server) != Config->ulines.end());
37 int InspIRCd::OperPassCompare(const char* data,const char* input, int tagnumber)
40 FOREACH_RESULT_I(this,I_OnOperCompare,OnOperCompare(data, input, tagnumber))
41 Log(DEBUG,"OperPassCompare: %d",MOD_RESULT);
46 Log(DEBUG,"strcmp fallback: '%s' '%s' %d",data,input,strcmp(data,input));
47 return strcmp(data,input);
50 long InspIRCd::Duration(const char* str)
56 if ((!strchr(str,'s')) && (!strchr(str,'m')) && (!strchr(str,'h')) && (!strchr(str,'d')) && (!strchr(str,'w')) && (!strchr(str,'y')))
60 return Duration(n.c_str());
63 for (char* i = (char*)str; *i; i++)
65 // if we have digits, build up a string for the value in n_field,
66 // up to 10 digits in size.
67 if ((*i >= '0') && (*i <= '9'))
69 strlcat(n_field,i,10);
73 // we dont have a digit, check for numeric tokens
77 total += atoi(n_field);
81 total += (atoi(n_field)*duration_m);
85 total += (atoi(n_field)*duration_h);
89 total += (atoi(n_field)*duration_d);
93 total += (atoi(n_field)*duration_w);
97 total += (atoi(n_field)*duration_y);
103 // add trailing seconds
104 total += atoi(n_field);
109 /* LoopCall is used to call a command classes handler repeatedly based on the contents of a comma seperated list.
110 * There are two overriden versions of this method, one of which takes two potential lists and the other takes one.
111 * We need a version which takes two potential lists for JOIN, because a JOIN may contain two lists of items at once,
112 * the channel names and their keys as follows:
113 * JOIN #chan1,#chan2,#chan3 key1,,key3
114 * Therefore, we need to deal with both lists concurrently. The first instance of this method does that by creating
115 * two instances of irc::commasepstream and reading them both together until the first runs out of tokens.
116 * The second version is much simpler and just has the one stream to read, and is used in NAMES, WHOIS, PRIVMSG etc.
117 * Both will only parse until they reach ServerInstance->Config->MaxTargets number of targets, to stop abuse via spam.
119 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere, unsigned int extra)
121 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
122 * which called us just carries on as it was.
124 if (!strchr(parameters[splithere],','))
127 /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
128 * By using std::map (thanks for the idea w00t) we can cut this down a ton.
131 std::map<irc::string, bool> dupes;
133 /* Create two lists, one for channel names, one for keys
135 irc::commasepstream items1(parameters[splithere]);
136 irc::commasepstream items2(parameters[extra]);
137 std::string item = "*";
138 unsigned int max = 0;
140 /* Attempt to iterate these lists and call the command objech
141 * which called us, for every parameter pair until there are
142 * no more left to parse.
144 while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
146 if (dupes.find(item.c_str()) == dupes.end())
148 const char* new_parameters[127];
150 for (int t = 0; (t < pcnt) && (t < 127); t++)
151 new_parameters[t] = parameters[t];
153 std::string extrastuff = items2.GetToken();
155 new_parameters[splithere] = item.c_str();
156 new_parameters[extra] = extrastuff.c_str();
158 if (CommandObj->Handle(new_parameters,pcnt,user) == CMD_USER_DELETED)
161 dupes[item.c_str()] = true;
167 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere)
169 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
170 * which called us just carries on as it was.
172 if (!strchr(parameters[splithere],','))
175 std::map<irc::string, bool> dupes;
177 /* Only one commasepstream here */
178 ServerInstance->Log(DEBUG,"Splitting '%s'",parameters[splithere]);
179 irc::commasepstream items1(parameters[splithere]);
180 std::string item = "*";
181 unsigned int max = 0;
183 /* Parse the commasepstream until there are no tokens remaining.
184 * Each token we parse out, call the command handler that called us
187 while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
189 if (dupes.find(item.c_str()) == dupes.end())
191 const char* new_parameters[127];
193 for (int t = 0; (t < pcnt) && (t < 127); t++)
194 new_parameters[t] = parameters[t];
196 new_parameters[splithere] = item.c_str();
198 parameters[splithere] = item.c_str();
200 /* Execute the command handler over and over. If someone pulls our user
201 * record out from under us (e.g. if we /kill a comma sep list, and we're
202 * in that list ourselves) abort if we're gone.
204 if (CommandObj->Handle(new_parameters,pcnt,user) == CMD_USER_DELETED)
207 dupes[item.c_str()] = true;
210 /* By returning 1 we tell our caller that nothing is to be done,
211 * as all the previous calls handled the data. This makes the parent
212 * return without doing any processing.
217 bool CommandParser::IsValidCommand(const std::string &commandname, int pcnt, userrec * user)
219 nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
221 if (n != cmdlist.end())
223 if ((pcnt>=n->second->min_params) && (n->second->source != "<core>"))
225 if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
227 if (n->second->flags_needed)
229 return ((user->HasPermission(commandname)) || (ServerInstance->ULine(user->server)));
238 command_t* CommandParser::GetHandler(const std::string &commandname)
240 nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
241 if (n != cmdlist.end())
247 // calls a handler function for a command
249 CmdResult CommandParser::CallHandler(const std::string &commandname,const char** parameters, int pcnt, userrec *user)
251 nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
253 if (n != cmdlist.end())
255 if (pcnt >= n->second->min_params)
257 if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
259 if (n->second->flags_needed)
261 if ((user->HasPermission(commandname)) || (!IS_LOCAL(user)))
263 return n->second->Handle(parameters,pcnt,user);
268 return n->second->Handle(parameters,pcnt,user);
276 void CommandParser::ProcessCommand(userrec *user, std::string &cmd)
278 const char *command_p[127];
280 irc::tokenstream tokens(cmd);
281 std::string command = tokens.GetToken();
283 while (((para[items] = tokens.GetToken()) != "") && (items < 127))
285 command_p[items] = para[items].c_str();
289 std::transform(command.begin(), command.end(), command.begin(), ::toupper);
292 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,false,cmd));
293 if (MOD_RESULT == 1) {
297 nspace::hash_map<std::string,command_t*>::iterator cm = cmdlist.find(command);
299 if (cm != cmdlist.end())
303 /* activity resets the ping pending timer */
304 user->nping = ServerInstance->Time() + user->pingmax;
305 if (cm->second->flags_needed)
307 if (!user->IsModeSet(cm->second->flags_needed))
309 user->WriteServ("481 %s :Permission Denied- You do not have the required operator privileges",user->nick);
312 if (!user->HasPermission(command))
314 user->WriteServ("481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command.c_str());
318 if ((user->registered == REG_ALL) && (!*user->oper) && (cm->second->IsDisabled()))
320 /* command is disabled! */
321 user->WriteServ("421 %s %s :This command has been disabled.",user->nick,command.c_str());
324 if (items < cm->second->min_params)
326 user->WriteServ("461 %s %s :Not enough parameters.", user->nick, command.c_str());
327 /* If syntax is given, display this as the 461 reply */
328 if ((ServerInstance->Config->SyntaxHints) && (cm->second->syntax.length()))
329 user->WriteServ("304 %s :SYNTAX %s %s", user->nick, cm->second->command.c_str(), cm->second->syntax.c_str());
332 if ((user->registered == REG_ALL) || (cm->second->WorksBeforeReg()))
334 /* ikky /stats counters */
335 cm->second->use_count++;
336 cm->second->total_bytes += cmd.length();
339 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,true,cmd));
344 * WARNING: nothing may come after the
345 * command handler call, as the handler
346 * may free the user structure!
348 CmdResult result = cm->second->Handle(command_p,items,user);
350 if (result != CMD_USER_DELETED)
352 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, items, user, result,cmd));
358 user->WriteServ("451 %s :You have not registered",command.c_str());
365 ServerInstance->stats->statsUnknown++;
366 user->WriteServ("421 %s %s :Unknown command",user->nick,command.c_str());
370 bool CommandParser::RemoveCommands(const char* source)
372 nspace::hash_map<std::string,command_t*>::iterator i,safei;
373 for (i = cmdlist.begin(); i != cmdlist.end(); i++)
377 if (safei != cmdlist.end())
379 RemoveCommand(safei, source);
382 safei = cmdlist.begin();
383 if (safei != cmdlist.end())
385 RemoveCommand(safei, source);
390 void CommandParser::RemoveCommand(nspace::hash_map<std::string,command_t*>::iterator safei, const char* source)
392 command_t* x = safei->second;
393 if (x->source == std::string(source))
395 cmdlist.erase(safei);
399 void CommandParser::ProcessBuffer(std::string &buffer,userrec *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)
413 ServerInstance->Log(DEBUG,"CMDIN: %s %s",user->nick,buffer.c_str());
414 this->ProcessCommand(user,buffer);
418 bool CommandParser::CreateCommand(command_t *f, void* so_handle)
422 if (RFCCommands.find(f->command) == RFCCommands.end())
424 RFCCommands[f->command] = so_handle;
425 ServerInstance->Log(DEBUG,"Monitoring RFC-specified reloadable command at %8x",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;
438 ServerInstance->Log(DEBUG,"Added command %s (%d parameters)", f->command.c_str(), f->min_params);
444 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
447 this->SetupCommandTable();
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)
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 this->LoadCommand(filename);
497 CmdResult cmd_reload::Handle(const char** parameters, int pcnt, userrec *user)
499 user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0]);
500 if (ServerInstance->Parser->ReloadCommand(parameters[0]))
502 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0]);
503 ServerInstance->WriteOpers("*** RELOAD: %s reloaded the '%s' command.", user->nick, parameters[0]);
508 user->WriteServ("NOTICE %s :*** Could not reload command '%s'", user->nick, parameters[0]);
513 void CommandParser::LoadCommand(const char* name)
515 char filename[MAXBUF];
517 command_t* (*cmd_factory_func)(InspIRCd*);
519 snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
520 ServerInstance->Log(DEBUG,"Load command: %s", filename);
522 h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
526 ServerInstance->Log(SPARSE, "Error loading core command: %s", dlerror());
530 if (this->FindSym((void **)&cmd_factory_func, h))
532 command_t* newcommand = cmd_factory_func(ServerInstance);
533 this->CreateCommand(newcommand, h);
537 void CommandParser::SetupCommandTable()
541 DIR* library = opendir(LIBRARYDIR);
544 dirent* entry = NULL;
545 while ((entry = readdir(library)))
547 if (match(entry->d_name, "cmd_*.so"))
549 this->LoadCommand(entry->d_name);
555 this->CreateCommand(new cmd_reload(ServerInstance));