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 (Config->ulines.find(server) != Config->ulines.end());
37 bool InspIRCd::SilentULine(const char* server)
39 std::map<irc::string,bool>::iterator n = Config->ulines.find(server);
40 if (n != Config->ulines.end())
45 int InspIRCd::OperPassCompare(const char* data,const char* input, int tagnumber)
48 FOREACH_RESULT_I(this,I_OnOperCompare,OnOperCompare(data, input, tagnumber))
53 return strcmp(data,input);
56 std::string InspIRCd::TimeString(time_t curtime)
58 return std::string(ctime(&curtime),24);
61 long InspIRCd::Duration(const char* str)
67 if ((!strchr(str,'s')) && (!strchr(str,'m')) && (!strchr(str,'h')) && (!strchr(str,'d')) && (!strchr(str,'w')) && (!strchr(str,'y')))
71 return Duration(n.c_str());
74 for (char* i = (char*)str; *i; i++)
76 // if we have digits, build up a string for the value in n_field,
77 // up to 10 digits in size.
78 if ((*i >= '0') && (*i <= '9'))
80 strlcat(n_field,i,10);
84 // we dont have a digit, check for numeric tokens
88 total += atoi(n_field);
92 total += (atoi(n_field)*duration_m);
96 total += (atoi(n_field)*duration_h);
100 total += (atoi(n_field)*duration_d);
104 total += (atoi(n_field)*duration_w);
108 total += (atoi(n_field)*duration_y);
114 // add trailing seconds
115 total += atoi(n_field);
120 /* LoopCall is used to call a command classes handler repeatedly based on the contents of a comma seperated list.
121 * There are two overriden versions of this method, one of which takes two potential lists and the other takes one.
122 * We need a version which takes two potential lists for JOIN, because a JOIN may contain two lists of items at once,
123 * the channel names and their keys as follows:
124 * JOIN #chan1,#chan2,#chan3 key1,,key3
125 * Therefore, we need to deal with both lists concurrently. The first instance of this method does that by creating
126 * two instances of irc::commasepstream and reading them both together until the first runs out of tokens.
127 * The second version is much simpler and just has the one stream to read, and is used in NAMES, WHOIS, PRIVMSG etc.
128 * Both will only parse until they reach ServerInstance->Config->MaxTargets number of targets, to stop abuse via spam.
130 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere, unsigned int extra)
132 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
133 * which called us just carries on as it was.
135 if (!strchr(parameters[splithere],','))
138 /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
139 * By using std::map (thanks for the idea w00t) we can cut this down a ton.
142 std::map<irc::string, bool> dupes;
144 /* Create two lists, one for channel names, one for keys
146 irc::commasepstream items1(parameters[splithere]);
147 irc::commasepstream items2(parameters[extra]);
148 std::string item = "*";
149 unsigned int max = 0;
151 /* Attempt to iterate these lists and call the command objech
152 * which called us, for every parameter pair until there are
153 * no more left to parse.
155 while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
157 if (dupes.find(item.c_str()) == dupes.end())
159 const char* new_parameters[127];
161 for (int t = 0; (t < pcnt) && (t < 127); t++)
162 new_parameters[t] = parameters[t];
164 std::string extrastuff = items2.GetToken();
166 new_parameters[splithere] = item.c_str();
167 new_parameters[extra] = extrastuff.c_str();
169 CommandObj->Handle(new_parameters,pcnt,user);
171 dupes[item.c_str()] = true;
177 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere)
179 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
180 * which called us just carries on as it was.
182 if (!strchr(parameters[splithere],','))
185 std::map<irc::string, bool> dupes;
187 /* Only one commasepstream here */
188 irc::commasepstream items1(parameters[splithere]);
189 std::string item = "*";
190 unsigned int max = 0;
192 /* Parse the commasepstream until there are no tokens remaining.
193 * Each token we parse out, call the command handler that called us
196 while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
198 if (dupes.find(item.c_str()) == dupes.end())
200 const char* new_parameters[127];
202 for (int t = 0; (t < pcnt) && (t < 127); t++)
203 new_parameters[t] = parameters[t];
205 new_parameters[splithere] = item.c_str();
207 parameters[splithere] = item.c_str();
209 /* Execute the command handler over and over. If someone pulls our user
210 * record out from under us (e.g. if we /kill a comma sep list, and we're
211 * in that list ourselves) abort if we're gone.
213 CommandObj->Handle(new_parameters,pcnt,user);
215 dupes[item.c_str()] = true;
218 /* By returning 1 we tell our caller that nothing is to be done,
219 * as all the previous calls handled the data. This makes the parent
220 * return without doing any processing.
225 bool CommandParser::IsValidCommand(const std::string &commandname, int pcnt, userrec * user)
227 nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
229 if (n != cmdlist.end())
231 if ((pcnt>=n->second->min_params) && (n->second->source != "<core>"))
233 if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
235 if (n->second->flags_needed)
237 return ((user->HasPermission(commandname)) || (ServerInstance->ULine(user->server)));
246 command_t* CommandParser::GetHandler(const std::string &commandname)
248 nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
249 if (n != cmdlist.end())
255 // calls a handler function for a command
257 CmdResult CommandParser::CallHandler(const std::string &commandname,const char** parameters, int pcnt, userrec *user)
259 nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
261 if (n != cmdlist.end())
263 if (pcnt >= n->second->min_params)
265 if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
267 if (n->second->flags_needed)
269 if ((user->HasPermission(commandname)) || (!IS_LOCAL(user)))
271 return n->second->Handle(parameters,pcnt,user);
276 return n->second->Handle(parameters,pcnt,user);
284 void CommandParser::ProcessCommand(userrec *user, std::string &cmd)
286 const char *command_p[127];
288 irc::tokenstream tokens(cmd);
290 tokens.GetToken(command);
292 /* A client sent a nick prefix on their command (ick)
293 * rhapsody and some braindead bouncers do this --
294 * the rfc says they shouldnt but also says the ircd should
295 * discard it if they do.
297 if (*command.c_str() == ':')
298 tokens.GetToken(command);
300 while (tokens.GetToken(para[items]) && (items < 127))
302 command_p[items] = para[items].c_str();
306 std::transform(command.begin(), command.end(), command.begin(), ::toupper);
309 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,false,cmd));
310 if (MOD_RESULT == 1) {
314 nspace::hash_map<std::string,command_t*>::iterator cm = cmdlist.find(command);
316 if (cm != cmdlist.end())
320 /* activity resets the ping pending timer */
321 user->nping = ServerInstance->Time() + user->pingmax;
322 if (cm->second->flags_needed)
324 if (!user->IsModeSet(cm->second->flags_needed))
326 user->WriteServ("481 %s :Permission Denied- You do not have the required operator privileges",user->nick);
329 if (!user->HasPermission(command))
331 user->WriteServ("481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command.c_str());
335 if ((user->registered == REG_ALL) && (!*user->oper) && (cm->second->IsDisabled()))
337 /* command is disabled! */
338 user->WriteServ("421 %s %s :This command has been disabled.",user->nick,command.c_str());
341 if (items < cm->second->min_params)
343 user->WriteServ("461 %s %s :Not enough parameters.", user->nick, command.c_str());
344 /* If syntax is given, display this as the 461 reply */
345 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (cm->second->syntax.length()))
346 user->WriteServ("304 %s :SYNTAX %s %s", user->nick, cm->second->command.c_str(), cm->second->syntax.c_str());
349 if ((user->registered == REG_ALL) || (cm->second->WorksBeforeReg()))
351 /* ikky /stats counters */
352 cm->second->use_count++;
353 cm->second->total_bytes += cmd.length();
356 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,true,cmd));
361 * WARNING: nothing may come after the
362 * command handler call, as the handler
363 * may free the user structure!
365 CmdResult result = cm->second->Handle(command_p,items,user);
367 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, items, user, result,cmd));
372 user->WriteServ("451 %s :You have not registered",command.c_str());
379 ServerInstance->stats->statsUnknown++;
380 user->WriteServ("421 %s %s :Unknown command",user->nick,command.c_str());
384 bool CommandParser::RemoveCommands(const char* source)
386 nspace::hash_map<std::string,command_t*>::iterator i,safei;
387 for (i = cmdlist.begin(); i != cmdlist.end(); i++)
391 if (safei != cmdlist.end())
393 RemoveCommand(safei, source);
396 safei = cmdlist.begin();
397 if (safei != cmdlist.end())
399 RemoveCommand(safei, source);
404 void CommandParser::RemoveCommand(nspace::hash_map<std::string,command_t*>::iterator safei, const char* source)
406 command_t* x = safei->second;
407 if (x->source == std::string(source))
409 cmdlist.erase(safei);
413 void CommandParser::ProcessBuffer(std::string &buffer,userrec *user)
415 std::string::size_type a;
420 while ((a = buffer.rfind("\n")) != std::string::npos)
422 while ((a = buffer.rfind("\r")) != std::string::npos)
429 ServerInstance->Log(DEBUG,"-> :%s %s",user->nick,buffer.c_str());
430 this->ProcessCommand(user,buffer);
435 bool CommandParser::CreateCommand(command_t *f, void* so_handle)
439 if (RFCCommands.find(f->command) == RFCCommands.end())
440 RFCCommands[f->command] = so_handle;
443 ServerInstance->Log(DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
448 /* create the command and push it onto the table */
449 if (cmdlist.find(f->command) == cmdlist.end())
451 cmdlist[f->command] = f;
457 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
460 this->SetupCommandTable();
463 bool CommandParser::FindSym(void** v, void* h)
465 *v = dlsym(h, "init_command");
466 const char* err = dlerror();
469 ServerInstance->Log(SPARSE, "Error loading core command: %s\n", err);
475 bool CommandParser::ReloadCommand(const char* cmd)
477 char filename[MAXBUF];
478 char commandname[MAXBUF];
481 for (const char* x = cmd; *x; x++, y++)
482 commandname[y] = toupper(*x);
486 SharedObjectList::iterator command = RFCCommands.find(commandname);
488 if (command != RFCCommands.end())
490 command_t* cmdptr = cmdlist.find(commandname)->second;
491 cmdlist.erase(cmdlist.find(commandname));
493 for (char* x = commandname; *x; x++)
498 dlclose(command->second);
499 RFCCommands.erase(command);
501 snprintf(filename, MAXBUF, "cmd_%s.so", commandname);
502 this->LoadCommand(filename);
510 CmdResult cmd_reload::Handle(const char** parameters, int pcnt, userrec *user)
512 user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0]);
513 if (ServerInstance->Parser->ReloadCommand(parameters[0]))
515 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0]);
516 ServerInstance->WriteOpers("*** RELOAD: %s reloaded the '%s' command.", user->nick, parameters[0]);
521 user->WriteServ("NOTICE %s :*** Could not reload command '%s'", user->nick, parameters[0]);
526 void CommandParser::LoadCommand(const char* name)
528 char filename[MAXBUF];
530 command_t* (*cmd_factory_func)(InspIRCd*);
532 snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
533 h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
537 ServerInstance->Log(SPARSE, "Error loading core command: %s", dlerror());
541 if (this->FindSym((void **)&cmd_factory_func, h))
543 command_t* newcommand = cmd_factory_func(ServerInstance);
544 this->CreateCommand(newcommand, h);
548 void CommandParser::SetupCommandTable()
552 DIR* library = opendir(LIBRARYDIR);
555 dirent* entry = NULL;
556 while ((entry = readdir(library)))
558 if (match(entry->d_name, "cmd_*.so"))
560 this->LoadCommand(entry->d_name);
566 this->CreateCommand(new cmd_reload(ServerInstance));