1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
18 #include "configreader.h"
26 #include "socketengine.h"
27 #include "userprocess.h"
29 #include "command_parse.h"
31 bool InspIRCd::ULine(const char* server)
38 return (find(Config->ulines.begin(),Config->ulines.end(),server) != Config->ulines.end());
41 int InspIRCd::OperPassCompare(const char* data,const char* input)
44 FOREACH_RESULT_I(this,I_OnOperCompare,OnOperCompare(data,input))
45 Log(DEBUG,"OperPassCompare: %d",MOD_RESULT);
50 Log(DEBUG,"strcmp fallback: '%s' '%s' %d",data,input,strcmp(data,input));
51 return strcmp(data,input);
54 long InspIRCd::Duration(const char* str)
60 if ((!strchr(str,'s')) && (!strchr(str,'m')) && (!strchr(str,'h')) && (!strchr(str,'d')) && (!strchr(str,'w')) && (!strchr(str,'y')))
64 return Duration(n.c_str());
67 for (char* i = (char*)str; *i; i++)
69 // if we have digits, build up a string for the value in n_field,
70 // up to 10 digits in size.
71 if ((*i >= '0') && (*i <= '9'))
73 strlcat(n_field,i,10);
77 // we dont have a digit, check for numeric tokens
81 total += atoi(n_field);
85 total += (atoi(n_field)*duration_m);
89 total += (atoi(n_field)*duration_h);
93 total += (atoi(n_field)*duration_d);
97 total += (atoi(n_field)*duration_w);
101 total += (atoi(n_field)*duration_y);
107 // add trailing seconds
108 total += atoi(n_field);
113 /* All other ircds when doing this check usually just look for a string of *@* or *. We're smarter than that, though. */
115 bool InspIRCd::HostMatchesEveryone(const std::string &mask, userrec* user)
118 char itrigger[MAXBUF];
121 if (!Config->ConfValue(Config->config_data, "insane","trigger", 0, itrigger, MAXBUF))
122 strlcpy(itrigger,"95.5",MAXBUF);
124 if (Config->ConfValueBool(Config->config_data, "insane","hostmasks", 0))
127 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
129 strlcpy(buffer,u->second->ident,MAXBUF);
130 charlcat(buffer,'@',MAXBUF);
131 strlcat(buffer,u->second->host,MAXBUF);
132 if (match(buffer,mask.c_str()))
135 float percent = ((float)matches / (float)clientlist.size()) * 100;
136 if (percent > (float)atof(itrigger))
138 WriteOpers("*** \2WARNING\2: %s tried to set a G/K/E line mask of %s, which covers %.2f%% of the network!",user->nick,mask.c_str(),percent);
144 bool InspIRCd::IPMatchesEveryone(const std::string &ip, userrec* user)
146 char itrigger[MAXBUF];
149 if (!Config->ConfValue(Config->config_data, "insane","trigger",0,itrigger,MAXBUF))
150 strlcpy(itrigger,"95.5",MAXBUF);
152 if (Config->ConfValueBool(Config->config_data, "insane","ipmasks",0))
155 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
157 if (match(u->second->GetIPString(),ip.c_str(),true))
161 float percent = ((float)matches / (float)clientlist.size()) * 100;
162 if (percent > (float)atof(itrigger))
164 WriteOpers("*** \2WARNING\2: %s tried to set a Z line mask of %s, which covers %.2f%% of the network!",user->nick,ip.c_str(),percent);
170 bool InspIRCd::NickMatchesEveryone(const std::string &nick, userrec* user)
172 char itrigger[MAXBUF];
175 if (!Config->ConfValue(Config->config_data, "insane","trigger",0,itrigger,MAXBUF))
176 strlcpy(itrigger,"95.5",MAXBUF);
178 if (Config->ConfValueBool(Config->config_data, "insane","nickmasks",0))
181 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
183 if (match(u->second->nick,nick.c_str()))
187 float percent = ((float)matches / (float)clientlist.size()) * 100;
188 if (percent > (float)atof(itrigger))
190 WriteOpers("*** \2WARNING\2: %s tried to set a Q line mask of %s, which covers %.2f%% of the network!",user->nick,nick.c_str(),percent);
196 /* LoopCall is used to call a command classes handler repeatedly based on the contents of a comma seperated list.
197 * There are two overriden versions of this method, one of which takes two potential lists and the other takes one.
198 * We need a version which takes two potential lists for JOIN, because a JOIN may contain two lists of items at once,
199 * the channel names and their keys as follows:
200 * JOIN #chan1,#chan2,#chan3 key1,,key3
201 * Therefore, we need to deal with both lists concurrently. The first instance of this method does that by creating
202 * two instances of irc::commasepstream and reading them both together until the first runs out of tokens.
203 * The second version is much simpler and just has the one stream to read, and is used in NAMES, WHOIS, PRIVMSG etc.
204 * Both will only parse until they reach ServerInstance->Config->MaxTargets number of targets, to stop abuse via spam.
206 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere, unsigned int extra)
208 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
209 * which called us just carries on as it was.
211 if (!strchr(parameters[splithere],','))
214 /* Create two lists, one for channel names, one for keys
216 irc::commasepstream items1(parameters[splithere]);
217 irc::commasepstream items2(parameters[extra]);
218 std::string item = "";
219 unsigned int max = 0;
221 /* Attempt to iterate these lists and call the command objech
222 * which called us, for every parameter pair until there are
223 * no more left to parse.
225 while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
227 std::string extrastuff = items2.GetToken();
228 parameters[splithere] = item.c_str();
229 parameters[extra] = extrastuff.c_str();
230 CommandObj->Handle(parameters,pcnt,user);
235 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere)
237 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
238 * which called us just carries on as it was.
240 if (!strchr(parameters[splithere],','))
243 /* Only one commasepstream here */
244 irc::commasepstream items1(parameters[splithere]);
245 std::string item = "";
246 unsigned int max = 0;
248 /* Parse the commasepstream until there are no tokens remaining.
249 * Each token we parse out, call the command handler that called us
252 while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
254 parameters[splithere] = item.c_str();
255 CommandObj->Handle(parameters,pcnt,user);
257 /* By returning 1 we tell our caller that nothing is to be done,
258 * as all the previous calls handled the data. This makes the parent
259 * return without doing any processing.
264 bool CommandParser::IsValidCommand(const std::string &commandname, int pcnt, userrec * user)
266 nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
268 if (n != cmdlist.end())
270 if ((pcnt>=n->second->min_params) && (n->second->source != "<core>"))
272 if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
274 if (n->second->flags_needed)
276 return ((user->HasPermission(commandname)) || (ServerInstance->ULine(user->server)));
285 // calls a handler function for a command
287 bool CommandParser::CallHandler(const std::string &commandname,const char** parameters, int pcnt, userrec *user)
289 nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
291 if (n != cmdlist.end())
293 if (pcnt >= n->second->min_params)
295 if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
297 if (n->second->flags_needed)
299 if ((user->HasPermission(commandname)) || (!IS_LOCAL(user)))
301 n->second->Handle(parameters,pcnt,user);
307 n->second->Handle(parameters,pcnt,user);
316 void CommandParser::ProcessCommand(userrec *user, std::string &cmd)
318 const char *command_p[127];
320 std::string para[127];
321 irc::tokenstream tokens(cmd);
322 std::string command = tokens.GetToken();
324 while (((para[items] = tokens.GetToken()) != "") && (items < 127))
325 command_p[items] = para[items++].c_str();
327 std::transform(command.begin(), command.end(), command.begin(), ::toupper);
330 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,false));
331 if (MOD_RESULT == 1) {
335 nspace::hash_map<std::string,command_t*>::iterator cm = cmdlist.find(command);
337 if (cm != cmdlist.end())
341 /* activity resets the ping pending timer */
342 user->nping = ServerInstance->Time() + user->pingmax;
343 if (cm->second->flags_needed)
345 if (!user->IsModeSet(cm->second->flags_needed))
347 user->WriteServ("481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
350 if (!user->HasPermission(command))
352 user->WriteServ("481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command.c_str());
356 if ((user->registered == REG_ALL) && (!*user->oper) && (cm->second->IsDisabled()))
358 /* command is disabled! */
359 user->WriteServ("421 %s %s :This command has been disabled.",user->nick,command.c_str());
362 if (items < cm->second->min_params)
364 user->WriteServ("461 %s %s :Not enough parameters.", user->nick, command.c_str());
365 /* If syntax is given, display this as the 461 reply */
366 if ((ServerInstance->Config->SyntaxHints) && (cm->second->syntax.length()))
367 user->WriteServ("304 %s :SYNTAX %s %s", user->nick, cm->second->command.c_str(), cm->second->syntax.c_str());
370 if ((user->registered == REG_ALL) || (cm->second->WorksBeforeReg()))
372 /* ikky /stats counters */
373 cm->second->use_count++;
374 cm->second->total_bytes += cmd.length();
377 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,true));
382 * WARNING: nothing may come after the
383 * command handler call, as the handler
384 * may free the user structure!
387 cm->second->Handle(command_p,items,user);
392 user->WriteServ("451 %s :You have not registered",command.c_str());
399 ServerInstance->stats->statsUnknown++;
400 user->WriteServ("421 %s %s :Unknown command",user->nick,command.c_str());
404 bool CommandParser::RemoveCommands(const char* source)
406 bool go_again = true;
412 for (nspace::hash_map<std::string,command_t*>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
414 command_t* x = i->second;
415 if (x->source == std::string(source))
417 ServerInstance->Log(DEBUG,"removecommands(%s) Removing dependent command: %s",x->source.c_str(),x->command.c_str());
428 void CommandParser::ProcessBuffer(std::string &buffer,userrec *user)
430 std::string::size_type a;
435 while ((a = buffer.rfind("\n")) != std::string::npos)
437 while ((a = buffer.rfind("\r")) != std::string::npos)
442 ServerInstance->Log(DEBUG,"CMDIN: %s %s",user->nick,buffer.c_str());
443 this->ProcessCommand(user,buffer);
447 bool CommandParser::CreateCommand(command_t *f, void* so_handle)
451 if (RFCCommands.find(f->command) == RFCCommands.end())
453 RFCCommands[f->command] = so_handle;
454 ServerInstance->Log(DEFAULT,"Monitoring RFC-specified reloadable command at %8x",so_handle);
458 ServerInstance->Log(DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
463 /* create the command and push it onto the table */
464 if (cmdlist.find(f->command) == cmdlist.end())
466 cmdlist[f->command] = f;
467 ServerInstance->Log(DEBUG,"Added command %s (%lu parameters)",f->command.c_str(),(unsigned long)f->min_params);
473 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
475 this->SetupCommandTable();
478 bool CommandParser::FindSym(void** v, void* h)
480 *v = dlsym(h, "init_command");
481 const char* err = dlerror();
484 ServerInstance->Log(SPARSE, "Error loading core command: %s\n", err);
490 bool CommandParser::ReloadCommand(const char* cmd)
492 char filename[MAXBUF];
493 char commandname[MAXBUF];
496 for (const char* x = cmd; *x; x++, y++)
497 commandname[y] = toupper(*x);
501 SharedObjectList::iterator command = RFCCommands.find(commandname);
503 if (command != RFCCommands.end())
505 command_t* cmdptr = cmdlist.find(commandname)->second;
506 cmdlist.erase(cmdlist.find(commandname));
508 for (char* x = commandname; *x; x++)
513 dlclose(command->second);
514 RFCCommands.erase(command);
516 sprintf(filename, "cmd_%s.so", commandname);
517 this->LoadCommand(filename);
525 void cmd_reload::Handle(const char** parameters, int pcnt, userrec *user)
527 user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0]);
528 if (ServerInstance->Parser->ReloadCommand(parameters[0]))
529 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0]);
531 user->WriteServ("NOTICE %s :*** Could not reload command '%s'", user->nick, parameters[0]);
534 void CommandParser::LoadCommand(const char* name)
536 char filename[MAXBUF];
538 command_t* (*cmd_factory_func)(InspIRCd*);
540 snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
541 ServerInstance->Log(DEBUG,"Load command: %s", filename);
543 h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
547 ServerInstance->Log(SPARSE, "Error loading core command: %s", dlerror());
551 if (this->FindSym((void **)&cmd_factory_func, h))
553 command_t* newcommand = cmd_factory_func(ServerInstance);
554 this->CreateCommand(newcommand, h);
558 void CommandParser::SetupCommandTable()
562 DIR* library = opendir(LIBRARYDIR);
565 dirent* entry = NULL;
566 while ((entry = readdir(library)))
568 if (match(entry->d_name, "cmd_*.so"))
570 this->LoadCommand(entry->d_name);
576 this->CreateCommand(new cmd_reload(ServerInstance));