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"
21 #include "socketengine.h"
23 #include "command_parse.h"
25 /* Directory Searching for Unix-Only */
31 bool InspIRCd::ULine(const char* server)
38 return (Config->ulines.find(server) != Config->ulines.end());
41 bool InspIRCd::SilentULine(const char* server)
43 std::map<irc::string,bool>::iterator n = Config->ulines.find(server);
44 if (n != Config->ulines.end())
49 int InspIRCd::OperPassCompare(const char* data,const char* input, int tagnumber)
52 FOREACH_RESULT_I(this,I_OnOperCompare,OnOperCompare(data, input, tagnumber))
57 return strcmp(data,input);
60 std::string InspIRCd::TimeString(time_t curtime)
62 return std::string(ctime(&curtime),24);
65 long InspIRCd::Duration(const char* str)
71 if ((!strchr(str,'s')) && (!strchr(str,'m')) && (!strchr(str,'h')) && (!strchr(str,'d')) && (!strchr(str,'w')) && (!strchr(str,'y')))
75 return Duration(n.c_str());
78 for (char* i = (char*)str; *i; i++)
80 // if we have digits, build up a string for the value in n_field,
81 // up to 10 digits in size.
82 if ((*i >= '0') && (*i <= '9'))
84 strlcat(n_field,i,10);
88 // we dont have a digit, check for numeric tokens
92 total += atoi(n_field);
96 total += (atoi(n_field)*duration_m);
100 total += (atoi(n_field)*duration_h);
104 total += (atoi(n_field)*duration_d);
108 total += (atoi(n_field)*duration_w);
112 total += (atoi(n_field)*duration_y);
118 // add trailing seconds
119 total += atoi(n_field);
124 /* LoopCall is used to call a command classes handler repeatedly based on the contents of a comma seperated list.
125 * There are two overriden versions of this method, one of which takes two potential lists and the other takes one.
126 * We need a version which takes two potential lists for JOIN, because a JOIN may contain two lists of items at once,
127 * the channel names and their keys as follows:
128 * JOIN #chan1,#chan2,#chan3 key1,,key3
129 * Therefore, we need to deal with both lists concurrently. The first instance of this method does that by creating
130 * two instances of irc::commasepstream and reading them both together until the first runs out of tokens.
131 * The second version is much simpler and just has the one stream to read, and is used in NAMES, WHOIS, PRIVMSG etc.
132 * Both will only parse until they reach ServerInstance->Config->MaxTargets number of targets, to stop abuse via spam.
134 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere, unsigned int extra)
136 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
137 * which called us just carries on as it was.
139 if (!strchr(parameters[splithere],','))
142 /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
143 * By using std::map (thanks for the idea w00t) we can cut this down a ton.
146 std::map<irc::string, bool> dupes;
148 /* Create two lists, one for channel names, one for keys
150 irc::commasepstream items1(parameters[splithere]);
151 irc::commasepstream items2(parameters[extra]);
152 std::string item = "*";
153 unsigned int max = 0;
155 /* Attempt to iterate these lists and call the command objech
156 * which called us, for every parameter pair until there are
157 * no more left to parse.
159 while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
161 if (dupes.find(item.c_str()) == dupes.end())
163 const char* new_parameters[127];
165 for (int t = 0; (t < pcnt) && (t < 127); t++)
166 new_parameters[t] = parameters[t];
168 std::string extrastuff = items2.GetToken();
170 new_parameters[splithere] = item.c_str();
171 new_parameters[extra] = extrastuff.c_str();
173 CommandObj->Handle(new_parameters,pcnt,user);
175 dupes[item.c_str()] = true;
181 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere)
183 /* First check if we have more than one item in the list, if we don't we return zero here and the handler
184 * which called us just carries on as it was.
186 if (!strchr(parameters[splithere],','))
189 std::map<irc::string, bool> dupes;
191 /* Only one commasepstream here */
192 irc::commasepstream items1(parameters[splithere]);
193 std::string item = "*";
194 unsigned int max = 0;
196 /* Parse the commasepstream until there are no tokens remaining.
197 * Each token we parse out, call the command handler that called us
200 while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
202 if (dupes.find(item.c_str()) == dupes.end())
204 const char* new_parameters[127];
206 for (int t = 0; (t < pcnt) && (t < 127); t++)
207 new_parameters[t] = parameters[t];
209 new_parameters[splithere] = item.c_str();
211 parameters[splithere] = item.c_str();
213 /* Execute the command handler over and over. If someone pulls our user
214 * record out from under us (e.g. if we /kill a comma sep list, and we're
215 * in that list ourselves) abort if we're gone.
217 CommandObj->Handle(new_parameters,pcnt,user);
219 dupes[item.c_str()] = true;
222 /* By returning 1 we tell our caller that nothing is to be done,
223 * as all the previous calls handled the data. This makes the parent
224 * return without doing any processing.
229 bool CommandParser::IsValidCommand(const std::string &commandname, int pcnt, userrec * user)
231 command_table::iterator n = cmdlist.find(commandname);
233 if (n != cmdlist.end())
235 if ((pcnt>=n->second->min_params) && (n->second->source != "<core>"))
237 if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
239 if (n->second->flags_needed)
241 return ((user->HasPermission(commandname)) || (ServerInstance->ULine(user->server)));
250 command_t* CommandParser::GetHandler(const std::string &commandname)
252 command_table::iterator n = cmdlist.find(commandname);
253 if (n != cmdlist.end())
259 // calls a handler function for a command
261 CmdResult CommandParser::CallHandler(const std::string &commandname,const char** parameters, int pcnt, userrec *user)
263 command_table::iterator n = cmdlist.find(commandname);
265 if (n != cmdlist.end())
267 if (pcnt >= n->second->min_params)
269 if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
271 if (n->second->flags_needed)
273 if ((user->HasPermission(commandname)) || (!IS_LOCAL(user)))
275 return n->second->Handle(parameters,pcnt,user);
280 return n->second->Handle(parameters,pcnt,user);
288 void CommandParser::ProcessCommand(userrec *user, std::string &cmd)
290 const char *command_p[127];
292 irc::tokenstream tokens(cmd);
294 tokens.GetToken(command);
296 /* A client sent a nick prefix on their command (ick)
297 * rhapsody and some braindead bouncers do this --
298 * the rfc says they shouldnt but also says the ircd should
299 * discard it if they do.
301 if (*command.c_str() == ':')
302 tokens.GetToken(command);
304 while (tokens.GetToken(para[items]) && (items < 127))
306 command_p[items] = para[items].c_str();
310 std::transform(command.begin(), command.end(), command.begin(), ::toupper);
313 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,false,cmd));
314 if (MOD_RESULT == 1) {
318 command_table::iterator cm = cmdlist.find(command);
320 if (cm != cmdlist.end())
324 /* activity resets the ping pending timer */
325 user->nping = ServerInstance->Time() + user->pingmax;
326 if (cm->second->flags_needed)
328 if (!user->IsModeSet(cm->second->flags_needed))
330 user->WriteServ("481 %s :Permission Denied- You do not have the required operator privileges",user->nick);
333 if (!user->HasPermission(command))
335 user->WriteServ("481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command.c_str());
339 if ((user->registered == REG_ALL) && (!IS_OPER(user)) && (cm->second->IsDisabled()))
341 /* command is disabled! */
342 user->WriteServ("421 %s %s :This command has been disabled.",user->nick,command.c_str());
345 if (items < cm->second->min_params)
347 user->WriteServ("461 %s %s :Not enough parameters.", user->nick, command.c_str());
348 /* If syntax is given, display this as the 461 reply */
349 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (cm->second->syntax.length()))
350 user->WriteServ("304 %s :SYNTAX %s %s", user->nick, cm->second->command.c_str(), cm->second->syntax.c_str());
353 if ((user->registered == REG_ALL) || (cm->second->WorksBeforeReg()))
355 /* ikky /stats counters */
356 cm->second->use_count++;
357 cm->second->total_bytes += cmd.length();
360 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,true,cmd));
365 * WARNING: nothing may come after the
366 * command handler call, as the handler
367 * may free the user structure!
369 CmdResult result = cm->second->Handle(command_p,items,user);
371 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, items, user, result,cmd));
376 user->WriteServ("451 %s :You have not registered",command.c_str());
383 ServerInstance->stats->statsUnknown++;
384 user->WriteServ("421 %s %s :Unknown command",user->nick,command.c_str());
388 bool CommandParser::RemoveCommands(const char* source)
390 command_table::iterator i,safei;
391 for (i = cmdlist.begin(); i != cmdlist.end(); i++)
395 if (safei != cmdlist.end())
397 RemoveCommand(safei, source);
400 safei = cmdlist.begin();
401 if (safei != cmdlist.end())
403 RemoveCommand(safei, source);
408 void CommandParser::RemoveCommand(command_table::iterator safei, const char* source)
410 command_t* x = safei->second;
411 if (x->source == std::string(source))
413 cmdlist.erase(safei);
417 void CommandParser::ProcessBuffer(std::string &buffer,userrec *user)
419 std::string::size_type a;
424 while ((a = buffer.rfind("\n")) != std::string::npos)
426 while ((a = buffer.rfind("\r")) != std::string::npos)
433 ServerInstance->Log(DEBUG,"C[%d] -> :%s %s",user->GetFd(), user->nick, buffer.c_str());
434 this->ProcessCommand(user,buffer);
439 bool CommandParser::CreateCommand(command_t *f, void* so_handle)
443 if (RFCCommands.find(f->command) == RFCCommands.end())
444 RFCCommands[f->command] = so_handle;
447 ServerInstance->Log(DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
452 /* create the command and push it onto the table */
453 if (cmdlist.find(f->command) == cmdlist.end())
455 cmdlist[f->command] = f;
461 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
464 this->SetupCommandTable();
467 bool CommandParser::FindSym(void** v, void* h)
469 *v = dlsym(h, "init_command");
470 const char* err = dlerror();
473 ServerInstance->Log(SPARSE, "Error loading core command: %s\n", err);
479 bool CommandParser::ReloadCommand(const char* cmd)
481 char filename[MAXBUF];
482 char commandname[MAXBUF];
485 for (const char* x = cmd; *x; x++, y++)
486 commandname[y] = toupper(*x);
490 SharedObjectList::iterator command = RFCCommands.find(commandname);
492 if (command != RFCCommands.end())
494 command_t* cmdptr = cmdlist.find(commandname)->second;
495 cmdlist.erase(cmdlist.find(commandname));
497 for (char* x = commandname; *x; x++)
502 dlclose(command->second);
503 RFCCommands.erase(command);
505 snprintf(filename, MAXBUF, "cmd_%s.so", commandname);
506 this->LoadCommand(filename);
514 CmdResult cmd_reload::Handle(const char** parameters, int pcnt, userrec *user)
516 user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0]);
517 if (ServerInstance->Parser->ReloadCommand(parameters[0]))
519 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0]);
520 ServerInstance->WriteOpers("*** RELOAD: %s reloaded the '%s' command.", user->nick, parameters[0]);
525 user->WriteServ("NOTICE %s :*** Could not reload command '%s'", user->nick, parameters[0]);
530 void CommandParser::LoadCommand(const char* name)
532 char filename[MAXBUF];
534 command_t* (*cmd_factory_func)(InspIRCd*);
536 snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
537 h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
541 ServerInstance->Log(SPARSE, "Error loading core command: %s", dlerror());
545 if (this->FindSym((void **)&cmd_factory_func, h))
547 command_t* newcommand = cmd_factory_func(ServerInstance);
548 this->CreateCommand(newcommand, h);
552 void CommandParser::SetupCommandTable()
556 printf("\nLoading core commands");
559 DIR* library = opendir(LIBRARYDIR);
562 dirent* entry = NULL;
563 while ((entry = readdir(library)))
565 if (match(entry->d_name, "cmd_*.so"))
569 this->LoadCommand(entry->d_name);
576 this->CreateCommand(new cmd_reload(ServerInstance));