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"
28 #include "command_parse.h"
30 bool InspIRCd::ULine(const char* server)
37 return (find(Config->ulines.begin(),Config->ulines.end(),server) != Config->ulines.end());
40 int InspIRCd::OperPassCompare(const char* data,const char* input, int tagnumber)
43 FOREACH_RESULT_I(this,I_OnOperCompare,OnOperCompare(data, input, tagnumber))
44 Log(DEBUG,"OperPassCompare: %d",MOD_RESULT);
49 Log(DEBUG,"strcmp fallback: '%s' '%s' %d",data,input,strcmp(data,input));
50 return strcmp(data,input);
53 long InspIRCd::Duration(const char* str)
59 if ((!strchr(str,'s')) && (!strchr(str,'m')) && (!strchr(str,'h')) && (!strchr(str,'d')) && (!strchr(str,'w')) && (!strchr(str,'y')))
63 return Duration(n.c_str());
66 for (char* i = (char*)str; *i; i++)
68 // if we have digits, build up a string for the value in n_field,
69 // up to 10 digits in size.
70 if ((*i >= '0') && (*i <= '9'))
72 strlcat(n_field,i,10);
76 // we dont have a digit, check for numeric tokens
80 total += atoi(n_field);
84 total += (atoi(n_field)*duration_m);
88 total += (atoi(n_field)*duration_h);
92 total += (atoi(n_field)*duration_d);
96 total += (atoi(n_field)*duration_w);
100 total += (atoi(n_field)*duration_y);
106 // add trailing seconds
107 total += atoi(n_field);
112 /* All other ircds when doing this check usually just look for a string of *@* or *. We're smarter than that, though. */
114 bool InspIRCd::HostMatchesEveryone(const std::string &mask, userrec* user)
117 char itrigger[MAXBUF];
120 if (!Config->ConfValue(Config->config_data, "insane","trigger", 0, itrigger, MAXBUF))
121 strlcpy(itrigger,"95.5",MAXBUF);
123 if (Config->ConfValueBool(Config->config_data, "insane","hostmasks", 0))
126 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
128 strlcpy(buffer,u->second->ident,MAXBUF);
129 charlcat(buffer,'@',MAXBUF);
130 strlcat(buffer,u->second->host,MAXBUF);
131 if (match(buffer,mask.c_str()))
134 float percent = ((float)matches / (float)clientlist.size()) * 100;
135 if (percent > (float)atof(itrigger))
137 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);
143 bool InspIRCd::IPMatchesEveryone(const std::string &ip, userrec* user)
145 char itrigger[MAXBUF];
148 if (!Config->ConfValue(Config->config_data, "insane","trigger",0,itrigger,MAXBUF))
149 strlcpy(itrigger,"95.5",MAXBUF);
151 if (Config->ConfValueBool(Config->config_data, "insane","ipmasks",0))
154 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
156 if (match(u->second->GetIPString(),ip.c_str(),true))
160 float percent = ((float)matches / (float)clientlist.size()) * 100;
161 if (percent > (float)atof(itrigger))
163 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);
169 bool InspIRCd::NickMatchesEveryone(const std::string &nick, userrec* user)
171 char itrigger[MAXBUF];
174 if (!Config->ConfValue(Config->config_data, "insane","trigger",0,itrigger,MAXBUF))
175 strlcpy(itrigger,"95.5",MAXBUF);
177 if (Config->ConfValueBool(Config->config_data, "insane","nickmasks",0))
180 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
182 if (match(u->second->nick,nick.c_str()))
186 float percent = ((float)matches / (float)clientlist.size()) * 100;
187 if (percent > (float)atof(itrigger))
189 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);
195 /* LoopCall is used to call a command classes handler repeatedly based on the contents of a comma seperated list.
196 * There are two overriden versions of this method, one of which takes two potential lists and the other takes one.
197 * We need a version which takes two potential lists for JOIN, because a JOIN may contain two lists of items at once,
198 * the channel names and their keys as follows:
199 * JOIN #chan1,#chan2,#chan3 key1,,key3
200 * Therefore, we need to deal with both lists concurrently. The first instance of this method does that by creating
201 * two instances of irc::commasepstream and reading them both together until the first runs out of tokens.
202 * The second version is much simpler and just has the one stream to read, and is used in NAMES, WHOIS, PRIVMSG etc.
203 * Both will only parse until they reach ServerInstance->Config->MaxTargets number of targets, to stop abuse via spam.
205 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere, unsigned int extra)
207 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
208 * which called us just carries on as it was.
210 if (!strchr(parameters[splithere],','))
213 /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
214 * By using std::map (thanks for the idea w00t) we can cut this down a ton.
217 std::map<irc::string, bool> dupes;
219 /* Create two lists, one for channel names, one for keys
221 irc::commasepstream items1(parameters[splithere]);
222 irc::commasepstream items2(parameters[extra]);
223 std::string item = "*";
224 unsigned int max = 0;
226 /* Attempt to iterate these lists and call the command objech
227 * which called us, for every parameter pair until there are
228 * no more left to parse.
230 while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
232 if (dupes.find(item.c_str()) == dupes.end())
234 const char* new_parameters[127];
236 for (int t = 0; (t < pcnt) && (t < 127); t++)
237 new_parameters[t] = parameters[t];
239 std::string extrastuff = items2.GetToken();
241 new_parameters[splithere] = item.c_str();
242 new_parameters[extra] = extrastuff.c_str();
244 if (CommandObj->Handle(new_parameters,pcnt,user) == CMD_USER_DELETED)
247 dupes[item.c_str()] = true;
253 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere)
255 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
256 * which called us just carries on as it was.
258 if (!strchr(parameters[splithere],','))
261 std::map<irc::string, bool> dupes;
263 /* Only one commasepstream here */
264 ServerInstance->Log(DEBUG,"Splitting '%s'",parameters[splithere]);
265 irc::commasepstream items1(parameters[splithere]);
266 std::string item = "*";
267 unsigned int max = 0;
269 /* Parse the commasepstream until there are no tokens remaining.
270 * Each token we parse out, call the command handler that called us
273 while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
275 if (dupes.find(item.c_str()) == dupes.end())
277 const char* new_parameters[127];
279 for (int t = 0; (t < pcnt) && (t < 127); t++)
280 new_parameters[t] = parameters[t];
282 new_parameters[splithere] = item.c_str();
284 parameters[splithere] = item.c_str();
286 /* Execute the command handler over and over. If someone pulls our user
287 * record out from under us (e.g. if we /kill a comma sep list, and we're
288 * in that list ourselves) abort if we're gone.
290 if (CommandObj->Handle(new_parameters,pcnt,user) == CMD_USER_DELETED)
293 dupes[item.c_str()] = true;
296 /* By returning 1 we tell our caller that nothing is to be done,
297 * as all the previous calls handled the data. This makes the parent
298 * return without doing any processing.
303 bool CommandParser::IsValidCommand(const std::string &commandname, int pcnt, userrec * user)
305 nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
307 if (n != cmdlist.end())
309 if ((pcnt>=n->second->min_params) && (n->second->source != "<core>"))
311 if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
313 if (n->second->flags_needed)
315 return ((user->HasPermission(commandname)) || (ServerInstance->ULine(user->server)));
324 command_t* CommandParser::GetHandler(const std::string &commandname)
326 nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
327 if (n != cmdlist.end())
333 // calls a handler function for a command
335 CmdResult CommandParser::CallHandler(const std::string &commandname,const char** parameters, int pcnt, userrec *user)
337 nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
339 if (n != cmdlist.end())
341 if (pcnt >= n->second->min_params)
343 if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
345 if (n->second->flags_needed)
347 if ((user->HasPermission(commandname)) || (!IS_LOCAL(user)))
349 return n->second->Handle(parameters,pcnt,user);
354 return n->second->Handle(parameters,pcnt,user);
362 void CommandParser::ProcessCommand(userrec *user, std::string &cmd)
364 const char *command_p[127];
366 irc::tokenstream tokens(cmd);
367 std::string command = tokens.GetToken();
369 while (((para[items] = tokens.GetToken()) != "") && (items < 127))
371 command_p[items] = para[items].c_str();
375 std::transform(command.begin(), command.end(), command.begin(), ::toupper);
378 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,false,cmd));
379 if (MOD_RESULT == 1) {
383 nspace::hash_map<std::string,command_t*>::iterator cm = cmdlist.find(command);
385 if (cm != cmdlist.end())
389 /* activity resets the ping pending timer */
390 user->nping = ServerInstance->Time() + user->pingmax;
391 if (cm->second->flags_needed)
393 if (!user->IsModeSet(cm->second->flags_needed))
395 user->WriteServ("481 %s :Permission Denied- You do not have the required operator privileges",user->nick);
398 if (!user->HasPermission(command))
400 user->WriteServ("481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command.c_str());
404 if ((user->registered == REG_ALL) && (!*user->oper) && (cm->second->IsDisabled()))
406 /* command is disabled! */
407 user->WriteServ("421 %s %s :This command has been disabled.",user->nick,command.c_str());
410 if (items < cm->second->min_params)
412 user->WriteServ("461 %s %s :Not enough parameters.", user->nick, command.c_str());
413 /* If syntax is given, display this as the 461 reply */
414 if ((ServerInstance->Config->SyntaxHints) && (cm->second->syntax.length()))
415 user->WriteServ("304 %s :SYNTAX %s %s", user->nick, cm->second->command.c_str(), cm->second->syntax.c_str());
418 if ((user->registered == REG_ALL) || (cm->second->WorksBeforeReg()))
420 /* ikky /stats counters */
421 cm->second->use_count++;
422 cm->second->total_bytes += cmd.length();
425 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,true,cmd));
430 * WARNING: nothing may come after the
431 * command handler call, as the handler
432 * may free the user structure!
434 CmdResult result = cm->second->Handle(command_p,items,user);
436 if (result != CMD_USER_DELETED)
438 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, items, user, result,cmd));
444 user->WriteServ("451 %s :You have not registered",command.c_str());
451 ServerInstance->stats->statsUnknown++;
452 user->WriteServ("421 %s %s :Unknown command",user->nick,command.c_str());
456 bool CommandParser::RemoveCommands(const char* source)
458 bool go_again = true;
464 for (nspace::hash_map<std::string,command_t*>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
466 command_t* x = i->second;
467 if (x->source == std::string(source))
469 ServerInstance->Log(DEBUG,"removecommands(%s) Removing dependent command: %s",x->source.c_str(),x->command.c_str());
480 void CommandParser::ProcessBuffer(std::string &buffer,userrec *user)
482 std::string::size_type a;
487 while ((a = buffer.rfind("\n")) != std::string::npos)
489 while ((a = buffer.rfind("\r")) != std::string::npos)
494 ServerInstance->Log(DEBUG,"CMDIN: %s %s",user->nick,buffer.c_str());
495 this->ProcessCommand(user,buffer);
499 bool CommandParser::CreateCommand(command_t *f, void* so_handle)
503 if (RFCCommands.find(f->command) == RFCCommands.end())
505 RFCCommands[f->command] = so_handle;
506 ServerInstance->Log(DEFAULT,"Monitoring RFC-specified reloadable command at %8x",so_handle);
510 ServerInstance->Log(DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
515 /* create the command and push it onto the table */
516 if (cmdlist.find(f->command) == cmdlist.end())
518 cmdlist[f->command] = f;
519 ServerInstance->Log(DEBUG,"Added command %s (%lu parameters)",f->command.c_str(),(unsigned long)f->min_params);
525 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
528 this->SetupCommandTable();
531 bool CommandParser::FindSym(void** v, void* h)
533 *v = dlsym(h, "init_command");
534 const char* err = dlerror();
537 ServerInstance->Log(SPARSE, "Error loading core command: %s\n", err);
543 bool CommandParser::ReloadCommand(const char* cmd)
545 char filename[MAXBUF];
546 char commandname[MAXBUF];
549 for (const char* x = cmd; *x; x++, y++)
550 commandname[y] = toupper(*x);
554 SharedObjectList::iterator command = RFCCommands.find(commandname);
556 if (command != RFCCommands.end())
558 command_t* cmdptr = cmdlist.find(commandname)->second;
559 cmdlist.erase(cmdlist.find(commandname));
561 for (char* x = commandname; *x; x++)
566 dlclose(command->second);
567 RFCCommands.erase(command);
569 snprintf(filename, MAXBUF, "cmd_%s.so", commandname);
570 this->LoadCommand(filename);
578 CmdResult cmd_reload::Handle(const char** parameters, int pcnt, userrec *user)
580 user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0]);
581 if (ServerInstance->Parser->ReloadCommand(parameters[0]))
583 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0]);
584 ServerInstance->WriteOpers("*** RELOAD: %s reloaded the '%s' command.", user->nick, parameters[0]);
589 user->WriteServ("NOTICE %s :*** Could not reload command '%s'", user->nick, parameters[0]);
594 void CommandParser::LoadCommand(const char* name)
596 char filename[MAXBUF];
598 command_t* (*cmd_factory_func)(InspIRCd*);
600 snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
601 ServerInstance->Log(DEBUG,"Load command: %s", filename);
603 h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
607 ServerInstance->Log(SPARSE, "Error loading core command: %s", dlerror());
611 if (this->FindSym((void **)&cmd_factory_func, h))
613 command_t* newcommand = cmd_factory_func(ServerInstance);
614 this->CreateCommand(newcommand, h);
618 void CommandParser::SetupCommandTable()
622 DIR* library = opendir(LIBRARYDIR);
625 dirent* entry = NULL;
626 while ((entry = readdir(library)))
628 if (match(entry->d_name, "cmd_*.so"))
630 this->LoadCommand(entry->d_name);
636 this->CreateCommand(new cmd_reload(ServerInstance));