]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
Fix server prefix on JOIN.
[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         nspace::hash_map<std::string,command_t*>::iterator i,safei;
456         for (i = cmdlist.begin(); i != cmdlist.end(); i++)
457         {
458                 safei = i;
459                 safei++;
460                 if (safei != cmdlist.end())
461                 {
462                         RemoveCommand(safei, source);
463                 }
464         }
465         safei = cmdlist.begin();
466         if (safei != cmdlist.end())
467         {
468                 RemoveCommand(safei, source);
469         }
470         return true;
471 }
472
473 void CommandParser::RemoveCommand(nspace::hash_map<std::string,command_t*>::iterator safei, const char* source)
474 {
475         command_t* x = safei->second;
476         if (x->source == std::string(source))
477         {
478                 ServerInstance->Log(DEBUG,"removecommands(%s) Removing dependent command: %s",x->source.c_str(),x->command.c_str());
479                 cmdlist.erase(safei);
480         }
481 }
482
483 void CommandParser::ProcessBuffer(std::string &buffer,userrec *user)
484 {
485         std::string::size_type a;
486
487         if (!user)
488                 return;
489
490         while ((a = buffer.rfind("\n")) != std::string::npos)
491                 buffer.erase(a);
492         while ((a = buffer.rfind("\r")) != std::string::npos)
493                 buffer.erase(a);
494
495         if (buffer.length())
496         {
497                 ServerInstance->Log(DEBUG,"CMDIN: %s %s",user->nick,buffer.c_str());
498                 this->ProcessCommand(user,buffer);
499         }
500 }
501
502 bool CommandParser::CreateCommand(command_t *f, void* so_handle)
503 {
504         if (so_handle)
505         {
506                 if (RFCCommands.find(f->command) == RFCCommands.end())
507                 {
508                         RFCCommands[f->command] = so_handle;
509                         ServerInstance->Log(DEFAULT,"Monitoring RFC-specified reloadable command at %8x",so_handle);
510                 }
511                 else
512                 {
513                         ServerInstance->Log(DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
514                         return false;
515                 }
516         }
517
518         /* create the command and push it onto the table */
519         if (cmdlist.find(f->command) == cmdlist.end())
520         {
521                 cmdlist[f->command] = f;
522                 ServerInstance->Log(DEBUG,"Added command %s (%lu parameters)",f->command.c_str(),(unsigned long)f->min_params);
523                 return true;
524         }
525         else return false;
526 }
527
528 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
529 {
530         para.resize(128);
531         this->SetupCommandTable();
532 }
533
534 bool CommandParser::FindSym(void** v, void* h)
535 {
536         *v = dlsym(h, "init_command");
537         const char* err = dlerror();
538         if (err)
539         {
540                 ServerInstance->Log(SPARSE, "Error loading core command: %s\n", err);
541                 return false;
542         }
543         return true;
544 }
545
546 bool CommandParser::ReloadCommand(const char* cmd)
547 {
548         char filename[MAXBUF];
549         char commandname[MAXBUF];
550         int y = 0;
551
552         for (const char* x = cmd; *x; x++, y++)
553                 commandname[y] = toupper(*x);
554
555         commandname[y] = 0;
556
557         SharedObjectList::iterator command = RFCCommands.find(commandname);
558
559         if (command != RFCCommands.end())
560         {
561                 command_t* cmdptr = cmdlist.find(commandname)->second;
562                 cmdlist.erase(cmdlist.find(commandname));
563
564                 for (char* x = commandname; *x; x++)
565                         *x = tolower(*x);
566
567
568                 delete cmdptr;
569                 dlclose(command->second);
570                 RFCCommands.erase(command);
571
572                 snprintf(filename, MAXBUF, "cmd_%s.so", commandname);
573                 this->LoadCommand(filename);
574
575                 return true;
576         }
577
578         return false;
579 }
580
581 CmdResult cmd_reload::Handle(const char** parameters, int pcnt, userrec *user)
582 {
583         user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0]);
584         if (ServerInstance->Parser->ReloadCommand(parameters[0]))
585         {
586                 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0]);
587                 ServerInstance->WriteOpers("*** RELOAD: %s reloaded the '%s' command.", user->nick, parameters[0]);
588                 return CMD_SUCCESS;
589         }
590         else
591         {
592                 user->WriteServ("NOTICE %s :*** Could not reload command '%s'", user->nick, parameters[0]);
593                 return CMD_FAILURE;
594         }
595 }
596
597 void CommandParser::LoadCommand(const char* name)
598 {
599         char filename[MAXBUF];
600         void* h;
601         command_t* (*cmd_factory_func)(InspIRCd*);
602
603         snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
604         ServerInstance->Log(DEBUG,"Load command: %s", filename);
605
606         h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
607
608         if (!h)
609         {
610                 ServerInstance->Log(SPARSE, "Error loading core command: %s", dlerror());
611                 return;
612         }
613
614         if (this->FindSym((void **)&cmd_factory_func, h))
615         {
616                 command_t* newcommand = cmd_factory_func(ServerInstance);
617                 this->CreateCommand(newcommand, h);
618         }
619 }
620
621 void CommandParser::SetupCommandTable()
622 {
623         RFCCommands.clear();
624
625         DIR* library = opendir(LIBRARYDIR);
626         if (library)
627         {
628                 dirent* entry = NULL;
629                 while ((entry = readdir(library)))
630                 {
631                         if (match(entry->d_name, "cmd_*.so"))
632                         {
633                                 this->LoadCommand(entry->d_name);
634                         }
635                 }
636                 closedir(library);
637         }
638
639         this->CreateCommand(new cmd_reload(ServerInstance));
640 }
641