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