]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
Fix comma-seperated list handling by CommandParser::LoopCall, should fix /amsg etc.
[user/henk/code/inspircd.git] / src / command_parse.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
6  *                       E-mail:
7  *                <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *            the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 #include "inspircd.h"
18 #include "configreader.h"
19 #include <algorithm>
20 #include <dirent.h>
21 #include <dlfcn.h>
22 #include "users.h"
23 #include "modules.h"
24 #include "wildcard.h"
25 #include "xline.h"
26 #include "socketengine.h"
27 #include "socket.h"
28 #include "command_parse.h"
29
30 bool InspIRCd::ULine(const char* server)
31 {
32         if (!server)
33                 return false;
34         if (!*server)
35                 return true;
36
37         return (find(Config->ulines.begin(),Config->ulines.end(),server) != Config->ulines.end());
38 }
39
40 int InspIRCd::OperPassCompare(const char* data,const char* input)
41 {
42         int MOD_RESULT = 0;
43         FOREACH_RESULT_I(this,I_OnOperCompare,OnOperCompare(data,input))
44         Log(DEBUG,"OperPassCompare: %d",MOD_RESULT);
45         if (MOD_RESULT == 1)
46                 return 0;
47         if (MOD_RESULT == -1)
48                 return 1;
49         Log(DEBUG,"strcmp fallback: '%s' '%s' %d",data,input,strcmp(data,input));
50         return strcmp(data,input);
51 }
52
53 long InspIRCd::Duration(const char* str)
54 {
55         char n_field[MAXBUF];
56         long total = 0;
57         n_field[0] = 0;
58
59         if ((!strchr(str,'s')) && (!strchr(str,'m')) && (!strchr(str,'h')) && (!strchr(str,'d')) && (!strchr(str,'w')) && (!strchr(str,'y')))
60         {
61                 std::string n = str;
62                 n += 's';
63                 return Duration(n.c_str());
64         }
65         
66         for (char* i = (char*)str; *i; i++)
67         {
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'))
71                 {
72                         strlcat(n_field,i,10);
73                 }
74                 else
75                 {
76                         // we dont have a digit, check for numeric tokens
77                         switch (tolower(*i))
78                         {
79                                 case 's':
80                                         total += atoi(n_field);
81                                 break;
82
83                                 case 'm':
84                                         total += (atoi(n_field)*duration_m);
85                                 break;
86
87                                 case 'h':
88                                         total += (atoi(n_field)*duration_h);
89                                 break;
90
91                                 case 'd':
92                                         total += (atoi(n_field)*duration_d);
93                                 break;
94
95                                 case 'w':
96                                         total += (atoi(n_field)*duration_w);
97                                 break;
98
99                                 case 'y':
100                                         total += (atoi(n_field)*duration_y);
101                                 break;
102                         }
103                         n_field[0] = 0;
104                 }
105         }
106         // add trailing seconds
107         total += atoi(n_field);
108         
109         return total;
110 }
111
112 /* All other ircds when doing this check usually just look for a string of *@* or *. We're smarter than that, though. */
113
114 bool InspIRCd::HostMatchesEveryone(const std::string &mask, userrec* user)
115 {
116         char buffer[MAXBUF];
117         char itrigger[MAXBUF];
118         long matches = 0;
119         
120         if (!Config->ConfValue(Config->config_data, "insane","trigger", 0, itrigger, MAXBUF))
121                 strlcpy(itrigger,"95.5",MAXBUF);
122         
123         if (Config->ConfValueBool(Config->config_data, "insane","hostmasks", 0))
124                 return false;
125         
126         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
127         {
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()))
132                         matches++;
133         }
134         float percent = ((float)matches / (float)clientlist.size()) * 100;
135         if (percent > (float)atof(itrigger))
136         {
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);
138                 return true;
139         }
140         return false;
141 }
142
143 bool InspIRCd::IPMatchesEveryone(const std::string &ip, userrec* user)
144 {
145         char itrigger[MAXBUF];
146         long matches = 0;
147         
148         if (!Config->ConfValue(Config->config_data, "insane","trigger",0,itrigger,MAXBUF))
149                 strlcpy(itrigger,"95.5",MAXBUF);
150         
151         if (Config->ConfValueBool(Config->config_data, "insane","ipmasks",0))
152                 return false;
153         
154         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
155         {
156                 if (match(u->second->GetIPString(),ip.c_str(),true))
157                         matches++;
158         }
159         
160         float percent = ((float)matches / (float)clientlist.size()) * 100;
161         if (percent > (float)atof(itrigger))
162         {
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);
164                 return true;
165         }
166         return false;
167 }
168
169 bool InspIRCd::NickMatchesEveryone(const std::string &nick, userrec* user)
170 {
171         char itrigger[MAXBUF];
172         long matches = 0;
173         
174         if (!Config->ConfValue(Config->config_data, "insane","trigger",0,itrigger,MAXBUF))
175                 strlcpy(itrigger,"95.5",MAXBUF);
176         
177         if (Config->ConfValueBool(Config->config_data, "insane","nickmasks",0))
178                 return false;
179
180         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
181         {
182                 if (match(u->second->nick,nick.c_str()))
183                         matches++;
184         }
185         
186         float percent = ((float)matches / (float)clientlist.size()) * 100;
187         if (percent > (float)atof(itrigger))
188         {
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);
190                 return true;
191         }
192         return false;
193 }
194
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.
204  */
205 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere, unsigned int extra)
206 {
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.
209          */
210         if (!strchr(parameters[splithere],','))
211                 return 0;
212
213         /* Create two lists, one for channel names, one for keys
214          */
215         irc::commasepstream items1(parameters[splithere]);
216         irc::commasepstream items2(parameters[extra]);
217         std::string item = "*";
218         unsigned int max = 0;
219
220         /* Attempt to iterate these lists and call the command objech
221          * which called us, for every parameter pair until there are
222          * no more left to parse.
223          */
224         while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
225         {
226                 const char* new_parameters[127];
227
228                 for (int t = 0; (t < pcnt) && (t < 127); t++)
229                         new_parameters[t] = parameters[t];
230
231                 std::string extrastuff = items2.GetToken();
232
233                 new_parameters[splithere] = item.c_str();
234                 new_parameters[extra] = extrastuff.c_str();
235
236                 CommandObj->Handle(new_parameters,pcnt,user);
237         }
238         return 1;
239 }
240
241 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere)
242 {
243         /* First check if we have more than one item in the list, if we don't we return zero here and the handler
244          * which called us just carries on as it was.
245          */
246         if (!strchr(parameters[splithere],','))
247                 return 0;
248
249         /* Only one commasepstream here */
250         ServerInstance->Log(DEBUG,"Splitting '%s'",parameters[splithere]);
251         irc::commasepstream items1(parameters[splithere]);
252         std::string item = "*";
253         unsigned int max = 0;
254
255         /* Parse the commasepstream until there are no tokens remaining.
256          * Each token we parse out, call the command handler that called us
257          * with it
258          */
259         while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
260         {
261                 const char* new_parameters[127];
262
263                 for (int t = 0; (t < pcnt) && (t < 127); t++)
264                         new_parameters[t] = parameters[t];
265
266                 new_parameters[splithere] = item.c_str();
267
268                 parameters[splithere] = item.c_str();
269                 CommandObj->Handle(new_parameters,pcnt,user);
270         }
271         /* By returning 1 we tell our caller that nothing is to be done,
272          * as all the previous calls handled the data. This makes the parent
273          * return without doing any processing.
274          */
275         return 1;
276 }
277
278 bool CommandParser::IsValidCommand(const std::string &commandname, int pcnt, userrec * user)
279 {
280         nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
281
282         if (n != cmdlist.end())
283         {
284                 if ((pcnt>=n->second->min_params) && (n->second->source != "<core>"))
285                 {
286                         if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
287                         {
288                                 if (n->second->flags_needed)
289                                 {
290                                         return ((user->HasPermission(commandname)) || (ServerInstance->ULine(user->server)));
291                                 }
292                                 return true;
293                         }
294                 }
295         }
296         return false;
297 }
298
299 command_t* CommandParser::GetHandler(const std::string &commandname)
300 {
301         nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
302         if (n != cmdlist.end())
303                 return n->second;
304
305         return NULL;
306 }
307
308 // calls a handler function for a command
309
310 CmdResult CommandParser::CallHandler(const std::string &commandname,const char** parameters, int pcnt, userrec *user)
311 {
312         nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
313
314         if (n != cmdlist.end())
315         {
316                 if (pcnt >= n->second->min_params)
317                 {
318                         if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
319                         {
320                                 if (n->second->flags_needed)
321                                 {
322                                         if ((user->HasPermission(commandname)) || (!IS_LOCAL(user)))
323                                         {
324                                                 return n->second->Handle(parameters,pcnt,user);
325                                         }
326                                 }
327                                 else
328                                 {
329                                         return n->second->Handle(parameters,pcnt,user);
330                                 }
331                         }
332                 }
333         }
334         return CMD_INVALID;
335 }
336
337 void CommandParser::ProcessCommand(userrec *user, std::string &cmd)
338 {
339         const char *command_p[127];
340         int items = 0;
341         irc::tokenstream tokens(cmd);
342         std::string command = tokens.GetToken();
343
344         while (((para[items] = tokens.GetToken()) != "") && (items < 127))
345         {
346                 command_p[items] = para[items].c_str();
347                 items++;
348         }
349
350         std::transform(command.begin(), command.end(), command.begin(), ::toupper);
351                 
352         int MOD_RESULT = 0;
353         FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,false,cmd));
354         if (MOD_RESULT == 1) {
355                 return;
356         }
357
358         nspace::hash_map<std::string,command_t*>::iterator cm = cmdlist.find(command);
359         
360         if (cm != cmdlist.end())
361         {
362                 if (user)
363                 {
364                         /* activity resets the ping pending timer */
365                         user->nping = ServerInstance->Time() + user->pingmax;
366                         if (cm->second->flags_needed)
367                         {
368                                 if (!user->IsModeSet(cm->second->flags_needed))
369                                 {
370                                         user->WriteServ("481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
371                                         return;
372                                 }
373                                 if (!user->HasPermission(command))
374                                 {
375                                         user->WriteServ("481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command.c_str());
376                                         return;
377                                 }
378                         }
379                         if ((user->registered == REG_ALL) && (!*user->oper) && (cm->second->IsDisabled()))
380                         {
381                                 /* command is disabled! */
382                                 user->WriteServ("421 %s %s :This command has been disabled.",user->nick,command.c_str());
383                                 return;
384                         }
385                         if (items < cm->second->min_params)
386                         {
387                                 user->WriteServ("461 %s %s :Not enough parameters.", user->nick, command.c_str());
388                                 /* If syntax is given, display this as the 461 reply */
389                                 if ((ServerInstance->Config->SyntaxHints) && (cm->second->syntax.length()))
390                                         user->WriteServ("304 %s :SYNTAX %s %s", user->nick, cm->second->command.c_str(), cm->second->syntax.c_str());
391                                 return;
392                         }
393                         if ((user->registered == REG_ALL) || (cm->second->WorksBeforeReg()))
394                         {
395                                 /* ikky /stats counters */
396                                 cm->second->use_count++;
397                                 cm->second->total_bytes += cmd.length();
398
399                                 int MOD_RESULT = 0;
400                                 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,true,cmd));
401                                 if (MOD_RESULT == 1)
402                                         return;
403
404                                 /*
405                                  * WARNING: nothing may come after the
406                                  * command handler call, as the handler
407                                  * may free the user structure!
408                                  */
409                                 CmdResult result = cm->second->Handle(command_p,items,user);
410
411                                 if (result != CMD_USER_DELETED)
412                                 {
413                                         FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, items, user, result,cmd));
414                                 }
415                                 return;
416                         }
417                         else
418                         {
419                                 user->WriteServ("451 %s :You have not registered",command.c_str());
420                                 return;
421                         }
422                 }
423         }
424         else if (user)
425         {
426                 ServerInstance->stats->statsUnknown++;
427                 user->WriteServ("421 %s %s :Unknown command",user->nick,command.c_str());
428         }
429 }
430
431 bool CommandParser::RemoveCommands(const char* source)
432 {
433         bool go_again = true;
434
435         while (go_again)
436         {
437                 go_again = false;
438
439                 for (nspace::hash_map<std::string,command_t*>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
440                 {
441                         command_t* x = i->second;
442                         if (x->source == std::string(source))
443                         {
444                                 ServerInstance->Log(DEBUG,"removecommands(%s) Removing dependent command: %s",x->source.c_str(),x->command.c_str());
445                                 cmdlist.erase(i);
446                                 go_again = true;
447                                 break;
448                         }
449                 }
450         }
451
452         return true;
453 }
454
455 void CommandParser::ProcessBuffer(std::string &buffer,userrec *user)
456 {
457         std::string::size_type a;
458
459         if (!user)
460                 return;
461
462         while ((a = buffer.rfind("\n")) != std::string::npos)
463                 buffer.erase(a);
464         while ((a = buffer.rfind("\r")) != std::string::npos)
465                 buffer.erase(a);
466
467         if (buffer.length())
468         {
469                 ServerInstance->Log(DEBUG,"CMDIN: %s %s",user->nick,buffer.c_str());
470                 this->ProcessCommand(user,buffer);
471         }
472 }
473
474 bool CommandParser::CreateCommand(command_t *f, void* so_handle)
475 {
476         if (so_handle)
477         {
478                 if (RFCCommands.find(f->command) == RFCCommands.end())
479                 {
480                         RFCCommands[f->command] = so_handle;
481                         ServerInstance->Log(DEFAULT,"Monitoring RFC-specified reloadable command at %8x",so_handle);
482                 }
483                 else
484                 {
485                         ServerInstance->Log(DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
486                         return false;
487                 }
488         }
489
490         /* create the command and push it onto the table */
491         if (cmdlist.find(f->command) == cmdlist.end())
492         {
493                 cmdlist[f->command] = f;
494                 ServerInstance->Log(DEBUG,"Added command %s (%lu parameters)",f->command.c_str(),(unsigned long)f->min_params);
495                 return true;
496         }
497         else return false;
498 }
499
500 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
501 {
502         para.resize(128);
503         this->SetupCommandTable();
504 }
505
506 bool CommandParser::FindSym(void** v, void* h)
507 {
508         *v = dlsym(h, "init_command");
509         const char* err = dlerror();
510         if (err)
511         {
512                 ServerInstance->Log(SPARSE, "Error loading core command: %s\n", err);
513                 return false;
514         }
515         return true;
516 }
517
518 bool CommandParser::ReloadCommand(const char* cmd)
519 {
520         char filename[MAXBUF];
521         char commandname[MAXBUF];
522         int y = 0;
523
524         for (const char* x = cmd; *x; x++, y++)
525                 commandname[y] = toupper(*x);
526
527         commandname[y] = 0;
528
529         SharedObjectList::iterator command = RFCCommands.find(commandname);
530
531         if (command != RFCCommands.end())
532         {
533                 command_t* cmdptr = cmdlist.find(commandname)->second;
534                 cmdlist.erase(cmdlist.find(commandname));
535
536                 for (char* x = commandname; *x; x++)
537                         *x = tolower(*x);
538
539
540                 delete cmdptr;
541                 dlclose(command->second);
542                 RFCCommands.erase(command);
543
544                 snprintf(filename, MAXBUF, "cmd_%s.so", commandname);
545                 this->LoadCommand(filename);
546
547                 return true;
548         }
549
550         return false;
551 }
552
553 CmdResult cmd_reload::Handle(const char** parameters, int pcnt, userrec *user)
554 {
555         user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0]);
556         if (ServerInstance->Parser->ReloadCommand(parameters[0]))
557         {
558                 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0]);
559                 return CMD_SUCCESS;
560         }
561         else
562         {
563                 user->WriteServ("NOTICE %s :*** Could not reload command '%s'", user->nick, parameters[0]);
564                 return CMD_FAILURE;
565         }
566 }
567
568 void CommandParser::LoadCommand(const char* name)
569 {
570         char filename[MAXBUF];
571         void* h;
572         command_t* (*cmd_factory_func)(InspIRCd*);
573
574         snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
575         ServerInstance->Log(DEBUG,"Load command: %s", filename);
576
577         h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
578
579         if (!h)
580         {
581                 ServerInstance->Log(SPARSE, "Error loading core command: %s", dlerror());
582                 return;
583         }
584
585         if (this->FindSym((void **)&cmd_factory_func, h))
586         {
587                 command_t* newcommand = cmd_factory_func(ServerInstance);
588                 this->CreateCommand(newcommand, h);
589         }
590 }
591
592 void CommandParser::SetupCommandTable()
593 {
594         RFCCommands.clear();
595
596         DIR* library = opendir(LIBRARYDIR);
597         if (library)
598         {
599                 dirent* entry = NULL;
600                 while ((entry = readdir(library)))
601                 {
602                         if (match(entry->d_name, "cmd_*.so"))
603                         {
604                                 this->LoadCommand(entry->d_name);
605                         }
606                 }
607                 closedir(library);
608         }
609
610         this->CreateCommand(new cmd_reload(ServerInstance));
611 }
612