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 /* All other ircds when doing this check usually just look for a string of *@* or *. We're smarter than that, though. */
111 bool InspIRCd::HostMatchesEveryone(const std::string &mask, userrec* user)
114 char itrigger[MAXBUF];
117 if (!Config->ConfValue(Config->config_data, "insane","trigger", 0, itrigger, MAXBUF))
118 strlcpy(itrigger,"95.5",MAXBUF);
120 if (Config->ConfValueBool(Config->config_data, "insane","hostmasks", 0))
123 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
125 strlcpy(buffer,u->second->ident,MAXBUF);
126 charlcat(buffer,'@',MAXBUF);
127 strlcat(buffer,u->second->host,MAXBUF);
128 if (match(buffer,mask.c_str()))
131 float percent = ((float)matches / (float)clientlist.size()) * 100;
132 if (percent > (float)atof(itrigger))
134 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);
140 bool InspIRCd::IPMatchesEveryone(const std::string &ip, userrec* user)
142 char itrigger[MAXBUF];
145 if (!Config->ConfValue(Config->config_data, "insane","trigger",0,itrigger,MAXBUF))
146 strlcpy(itrigger,"95.5",MAXBUF);
148 if (Config->ConfValueBool(Config->config_data, "insane","ipmasks",0))
151 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
153 if (match(u->second->GetIPString(),ip.c_str(),true))
157 float percent = ((float)matches / (float)clientlist.size()) * 100;
158 if (percent > (float)atof(itrigger))
160 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);
166 bool InspIRCd::NickMatchesEveryone(const std::string &nick, userrec* user)
168 char itrigger[MAXBUF];
171 if (!Config->ConfValue(Config->config_data, "insane","trigger",0,itrigger,MAXBUF))
172 strlcpy(itrigger,"95.5",MAXBUF);
174 if (Config->ConfValueBool(Config->config_data, "insane","nickmasks",0))
177 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
179 if (match(u->second->nick,nick.c_str()))
183 float percent = ((float)matches / (float)clientlist.size()) * 100;
184 if (percent > (float)atof(itrigger))
186 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);
192 /* LoopCall is used to call a command classes handler repeatedly based on the contents of a comma seperated list.
193 * There are two overriden versions of this method, one of which takes two potential lists and the other takes one.
194 * We need a version which takes two potential lists for JOIN, because a JOIN may contain two lists of items at once,
195 * the channel names and their keys as follows:
196 * JOIN #chan1,#chan2,#chan3 key1,,key3
197 * Therefore, we need to deal with both lists concurrently. The first instance of this method does that by creating
198 * two instances of irc::commasepstream and reading them both together until the first runs out of tokens.
199 * The second version is much simpler and just has the one stream to read, and is used in NAMES, WHOIS, PRIVMSG etc.
200 * Both will only parse until they reach ServerInstance->Config->MaxTargets number of targets, to stop abuse via spam.
202 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere, unsigned int extra)
204 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
205 * which called us just carries on as it was.
207 if (!strchr(parameters[splithere],','))
210 /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
211 * By using std::map (thanks for the idea w00t) we can cut this down a ton.
214 std::map<irc::string, bool> dupes;
216 /* Create two lists, one for channel names, one for keys
218 irc::commasepstream items1(parameters[splithere]);
219 irc::commasepstream items2(parameters[extra]);
220 std::string item = "*";
221 unsigned int max = 0;
223 /* Attempt to iterate these lists and call the command objech
224 * which called us, for every parameter pair until there are
225 * no more left to parse.
227 while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
229 if (dupes.find(item.c_str()) == dupes.end())
231 const char* new_parameters[127];
233 for (int t = 0; (t < pcnt) && (t < 127); t++)
234 new_parameters[t] = parameters[t];
236 std::string extrastuff = items2.GetToken();
238 new_parameters[splithere] = item.c_str();
239 new_parameters[extra] = extrastuff.c_str();
241 if (CommandObj->Handle(new_parameters,pcnt,user) == CMD_USER_DELETED)
244 dupes[item.c_str()] = true;
250 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere)
252 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
253 * which called us just carries on as it was.
255 if (!strchr(parameters[splithere],','))
258 std::map<irc::string, bool> dupes;
260 /* Only one commasepstream here */
261 ServerInstance->Log(DEBUG,"Splitting '%s'",parameters[splithere]);
262 irc::commasepstream items1(parameters[splithere]);
263 std::string item = "*";
264 unsigned int max = 0;
266 /* Parse the commasepstream until there are no tokens remaining.
267 * Each token we parse out, call the command handler that called us
270 while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
272 if (dupes.find(item.c_str()) == dupes.end())
274 const char* new_parameters[127];
276 for (int t = 0; (t < pcnt) && (t < 127); t++)
277 new_parameters[t] = parameters[t];
279 new_parameters[splithere] = item.c_str();
281 parameters[splithere] = item.c_str();
283 /* Execute the command handler over and over. If someone pulls our user
284 * record out from under us (e.g. if we /kill a comma sep list, and we're
285 * in that list ourselves) abort if we're gone.
287 if (CommandObj->Handle(new_parameters,pcnt,user) == CMD_USER_DELETED)
290 dupes[item.c_str()] = true;
293 /* By returning 1 we tell our caller that nothing is to be done,
294 * as all the previous calls handled the data. This makes the parent
295 * return without doing any processing.
300 bool CommandParser::IsValidCommand(const std::string &commandname, int pcnt, userrec * user)
302 nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
304 if (n != cmdlist.end())
306 if ((pcnt>=n->second->min_params) && (n->second->source != "<core>"))
308 if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
310 if (n->second->flags_needed)
312 return ((user->HasPermission(commandname)) || (ServerInstance->ULine(user->server)));
321 command_t* CommandParser::GetHandler(const std::string &commandname)
323 nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
324 if (n != cmdlist.end())
330 // calls a handler function for a command
332 CmdResult CommandParser::CallHandler(const std::string &commandname,const char** parameters, int pcnt, userrec *user)
334 nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
336 if (n != cmdlist.end())
338 if (pcnt >= n->second->min_params)
340 if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
342 if (n->second->flags_needed)
344 if ((user->HasPermission(commandname)) || (!IS_LOCAL(user)))
346 return n->second->Handle(parameters,pcnt,user);
351 return n->second->Handle(parameters,pcnt,user);
359 void CommandParser::ProcessCommand(userrec *user, std::string &cmd)
361 const char *command_p[127];
363 irc::tokenstream tokens(cmd);
364 std::string command = tokens.GetToken();
366 while (((para[items] = tokens.GetToken()) != "") && (items < 127))
368 command_p[items] = para[items].c_str();
372 std::transform(command.begin(), command.end(), command.begin(), ::toupper);
375 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,false,cmd));
376 if (MOD_RESULT == 1) {
380 nspace::hash_map<std::string,command_t*>::iterator cm = cmdlist.find(command);
382 if (cm != cmdlist.end())
386 /* activity resets the ping pending timer */
387 user->nping = ServerInstance->Time() + user->pingmax;
388 if (cm->second->flags_needed)
390 if (!user->IsModeSet(cm->second->flags_needed))
392 user->WriteServ("481 %s :Permission Denied- You do not have the required operator privileges",user->nick);
395 if (!user->HasPermission(command))
397 user->WriteServ("481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command.c_str());
401 if ((user->registered == REG_ALL) && (!*user->oper) && (cm->second->IsDisabled()))
403 /* command is disabled! */
404 user->WriteServ("421 %s %s :This command has been disabled.",user->nick,command.c_str());
407 if (items < cm->second->min_params)
409 user->WriteServ("461 %s %s :Not enough parameters.", user->nick, command.c_str());
410 /* If syntax is given, display this as the 461 reply */
411 if ((ServerInstance->Config->SyntaxHints) && (cm->second->syntax.length()))
412 user->WriteServ("304 %s :SYNTAX %s %s", user->nick, cm->second->command.c_str(), cm->second->syntax.c_str());
415 if ((user->registered == REG_ALL) || (cm->second->WorksBeforeReg()))
417 /* ikky /stats counters */
418 cm->second->use_count++;
419 cm->second->total_bytes += cmd.length();
422 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,true,cmd));
427 * WARNING: nothing may come after the
428 * command handler call, as the handler
429 * may free the user structure!
431 CmdResult result = cm->second->Handle(command_p,items,user);
433 if (result != CMD_USER_DELETED)
435 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, items, user, result,cmd));
441 user->WriteServ("451 %s :You have not registered",command.c_str());
448 ServerInstance->stats->statsUnknown++;
449 user->WriteServ("421 %s %s :Unknown command",user->nick,command.c_str());
453 bool CommandParser::RemoveCommands(const char* source)
455 nspace::hash_map<std::string,command_t*>::iterator i,safei;
456 for (i = cmdlist.begin(); i != cmdlist.end(); i++)
460 if (safei != cmdlist.end())
462 RemoveCommand(safei, source);
465 safei = cmdlist.begin();
466 if (safei != cmdlist.end())
468 RemoveCommand(safei, source);
473 void CommandParser::RemoveCommand(nspace::hash_map<std::string,command_t*>::iterator safei, const char* source)
475 command_t* x = safei->second;
476 if (x->source == std::string(source))
478 ServerInstance->Log(DEBUG,"removecommands(%s) Removing dependent command: %s",x->source.c_str(),x->command.c_str());
479 cmdlist.erase(safei);
483 void CommandParser::ProcessBuffer(std::string &buffer,userrec *user)
485 std::string::size_type a;
490 while ((a = buffer.rfind("\n")) != std::string::npos)
492 while ((a = buffer.rfind("\r")) != std::string::npos)
497 ServerInstance->Log(DEBUG,"CMDIN: %s %s",user->nick,buffer.c_str());
498 this->ProcessCommand(user,buffer);
502 bool CommandParser::CreateCommand(command_t *f, void* so_handle)
506 if (RFCCommands.find(f->command) == RFCCommands.end())
508 RFCCommands[f->command] = so_handle;
509 ServerInstance->Log(DEFAULT,"Monitoring RFC-specified reloadable command at %8x",so_handle);
513 ServerInstance->Log(DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
518 /* create the command and push it onto the table */
519 if (cmdlist.find(f->command) == cmdlist.end())
521 cmdlist[f->command] = f;
522 ServerInstance->Log(DEBUG,"Added command %s (%lu parameters)",f->command.c_str(),(unsigned long)f->min_params);
528 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
531 this->SetupCommandTable();
534 bool CommandParser::FindSym(void** v, void* h)
536 *v = dlsym(h, "init_command");
537 const char* err = dlerror();
540 ServerInstance->Log(SPARSE, "Error loading core command: %s\n", err);
546 bool CommandParser::ReloadCommand(const char* cmd)
548 char filename[MAXBUF];
549 char commandname[MAXBUF];
552 for (const char* x = cmd; *x; x++, y++)
553 commandname[y] = toupper(*x);
557 SharedObjectList::iterator command = RFCCommands.find(commandname);
559 if (command != RFCCommands.end())
561 command_t* cmdptr = cmdlist.find(commandname)->second;
562 cmdlist.erase(cmdlist.find(commandname));
564 for (char* x = commandname; *x; x++)
569 dlclose(command->second);
570 RFCCommands.erase(command);
572 snprintf(filename, MAXBUF, "cmd_%s.so", commandname);
573 this->LoadCommand(filename);
581 CmdResult cmd_reload::Handle(const char** parameters, int pcnt, userrec *user)
583 user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0]);
584 if (ServerInstance->Parser->ReloadCommand(parameters[0]))
586 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0]);
587 ServerInstance->WriteOpers("*** RELOAD: %s reloaded the '%s' command.", user->nick, parameters[0]);
592 user->WriteServ("NOTICE %s :*** Could not reload command '%s'", user->nick, parameters[0]);
597 void CommandParser::LoadCommand(const char* name)
599 char filename[MAXBUF];
601 command_t* (*cmd_factory_func)(InspIRCd*);
603 snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
604 ServerInstance->Log(DEBUG,"Load command: %s", filename);
606 h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
610 ServerInstance->Log(SPARSE, "Error loading core command: %s", dlerror());
614 if (this->FindSym((void **)&cmd_factory_func, h))
616 command_t* newcommand = cmd_factory_func(ServerInstance);
617 this->CreateCommand(newcommand, h);
621 void CommandParser::SetupCommandTable()
625 DIR* library = opendir(LIBRARYDIR);
628 dirent* entry = NULL;
629 while ((entry = readdir(library)))
631 if (match(entry->d_name, "cmd_*.so"))
633 this->LoadCommand(entry->d_name);
639 this->CreateCommand(new cmd_reload(ServerInstance));